package com.xlx.users.interceptor;

import cn.hutool.jwt.JWT;
import com.xlx.common.utils.UsersLoginKey;
import com.xlx.users.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author xieluxing
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static String userskey = UsersLoginKey.USERS_KET;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取请求头中令牌
        String token = request.getHeader("Authorization");

        if(token.isBlank()){
            throw new RuntimeException("token无效!");
        }

        String value = redisTemplate.opsForValue().get(token);

        assert value != null;
        if (value.isBlank()) {
            throw new RuntimeException("token过期!");
        }

        //hutool里面有一个验证方法
        if (!JWT.of(token).setKey(userskey.getBytes()).verify()) {
            throw new RuntimeException("token无效!");
        }

        if (redisTemplate.getExpire(token, TimeUnit.HOURS)<=3){
            redisTemplate.opsForValue().set(token, value, 7, TimeUnit.DAYS);
        }

        Object usersId = JWT.of(token).getPayload("usersId");

        // 将商家id添加到本地线程中
        BaseContext.setCurrentId((String) usersId);
        return true;
    }
}